from datetime import datetime
from io import BytesIO

import xlwt
from django.shortcuts import HttpResponse
from django.urls import re_path

from stark.service.v1 import StarkHandler, Option
from web import models


class HostSubnetHandler(StarkHandler):
    list_display = [
        'ip_address',
        'ip_type',
        'depart',
        'app_name',
        'responsible_person',
        'last_change_date',
    ]

    def get_urls(self):
        """
        二次路由分发
        :return:
        """
        patterns = [
            re_path(r'^list/(?P<subnet_id>\d+)/$', self.wrapper(self.list_view), name=self.get_list_url_name),
            # re_path(r'^add/$', self.wrapper(self.add_view), name=self.get_add_url_name),
            # re_path(r'^change/(?P<pk>\d+)/$', self.wrapper(self.change_view),
            #         name=self.get_change_url_name),
            # re_path(r'^delete/(?P<pk>\d+)/$', self.wrapper(self.delete_view),
            #         name=self.get_delete_url_name)
        ]
        patterns.extend(self.extra_url())
        return patterns

    def get_add_btn(self, request, *args, **kwargs):
        return None

    def get_queryset(self, request, *args, **kwargs):
        subnet_id = kwargs.get('subnet_id')
        queryset = models.Hosts.objects.filter(ip_subnet_id=subnet_id)
        return queryset

    def get_list_display(self, request, *args, **kwargs):
        """
        预留列表页面显示字段的钩子函数
        :return:
        """
        value = []
        if self.list_display:
            value.extend(self.list_display)
        return value

    def action_multi_export(self, request, *args, **kwargs):
        '''
        导出excel
        :param request:
        :param args:
        :param kwargs:
        :return:
        '''
        subnet_id = kwargs.get('subnet_id')
        ip_subnet = models.IpSubnet.objects.filter(id=subnet_id).first()
        host_queryset = models.Hosts.objects.filter(ip_subnet=subnet_id)
        now_time = datetime.now().strftime('%Y-%m-%d')
        # 设置HTTPResponse的类型
        response = HttpResponse(content_type='application/vnd.ms-excel')
        response['Content-Disposition'] = 'attachment;filename=%s-%s.xls' % (ip_subnet.subnet, now_time)
        # 创建一个文件对象
        wb = xlwt.Workbook(encoding='utf8')
        # 创建一个sheet对象
        sheet = wb.add_sheet('sheet1')

        # 设置文件头的样式,这个不是必须的可以根据自己的需求进行更改

        # 写入文件标题
        sheet.write(0, 0, '序号')
        sheet.write(0, 1, 'IP地址')
        sheet.write(0, 2, '资产类型')
        sheet.write(0, 3, '使用单位')
        sheet.write(0, 4, '位置')
        sheet.write(0, 5, '负责人')
        sheet.write(0, 6, '应用名称/设备名称')
        sheet.write(0, 7, '变更日期')
        data_row = 1
        for host in host_queryset:
            ip_address = host.ip_address
            asset_type = host.ip_type.title
            depart = host.depart.title if host.depart else ""
            location = host.location
            responsible_person = host.responsible_person
            app_name = host.app_name
            last_change_date = host.last_change_date

            # 写入数据
            # UserTable.objects.all()这个是查询条件,可以根据自己的实际需求做调整.
            # for i in UserTable.objects.all():
            # 格式化datetime
            # pri_time = i.pri_date.strftime('%Y-%m-%d')
            # oper_time = i.operating_time.strftime('%Y-%m-%d')
            sheet.write(data_row, 0, data_row)
            sheet.write(data_row, 1, ip_address)
            sheet.write(data_row, 2, asset_type)
            sheet.write(data_row, 3, depart)
            sheet.write(data_row, 4, location)
            sheet.write(data_row, 5, responsible_person)
            sheet.write(data_row, 6, app_name)
            sheet.write(data_row, 7, last_change_date.strftime('%Y-%m-%d'))
            data_row = data_row + 1

        # 写出到IO
        output = BytesIO()
        wb.save(output)
        # 重新定位到开始
        output.seek(0)
        response.write(output.getvalue())
        return response

    action_multi_export.text = '导出EXCEL'
    action_list = [action_multi_export, ]

    search_list = ['location__contains', 'ip_address__contains']

    search_group = [Option('ip_type'), ]
